package com.rstar.readerbook;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class TxtList extends ListActivity{

		private List<File> txtList = new ArrayList<File>();
	    private MyApplication application;
	    
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.listview);	
			application = (MyApplication)getApplication();
			//SD卡的路径
			boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
	        if(sdCardExist){   
	        	File sdCardPath = Environment.getExternalStorageDirectory();
	        	
	        	File fileDir = new File(sdCardPath.toString()+"/txtBook");
	        	if(!fileDir.exists()){
	        		fileDir.mkdirs();
	        	}       	
	        	
	        	GetFiles(new File(sdCardPath.toString()+"/txtBook"));	
	        }else{
	        	Toast.makeText(this, R.string.please_insert_sd_card, Toast.LENGTH_SHORT).toString();
	        	TxtList.this.finish();
	        }        
		}
		
		public void  GetFiles(File filepath)
		{			
			File[]  files = filepath.listFiles();
			
			for(File  file:files)
			{
				if(file.isDirectory())
				{
					GetFiles(file);
				}
				else  if(file.getName().toLowerCase().endsWith(".txt"))
				{
					txtList.add(file);
				}
			}
			
			ArrayAdapter<Object>  adapter = new ArrayAdapter<Object>(this,android.R.layout.simple_list_item_1,FileToStr(txtList));
			setListAdapter(adapter);
			if(txtList.size()==0){
				Toast.makeText(TxtList.this, R.string.no_book_floder, Toast.LENGTH_SHORT).show();
				TxtList.this.finish();
			}
		}

		/**
		 * 把文件列表转换成字符串
		 * @param f
		 * @return
		 */
		public String[] FileToStr( List<File> f ){
			ArrayList<String> listStr = new ArrayList<String>();
			int i;
			for (i = 0; i < f.size(); i++) {
				String nameString = f.get(i).getName();
				listStr.add(nameString);
			}
			return listStr.toArray(new String[0]);
		}
		
		/**
		 * 当List中有点击时被激活
		 */
		protected void onListItemClick(ListView l, View v, int position, long id) {	
			File file = txtList.get(position); 		
			application.setFilePath(txtList.get(position).toString());			
			Intent i = new Intent(TxtList.this,ReaderBook.class);								
			startActivity(i);
		}
}
